const Koa = require('koa');
const app = new Koa();
require('./models');
const {koaBody} = require('koa-body');
const catchError = require('./middlewares/catcherr') // 统一异常
const result = require('./middlewares/result') // 统一返回结构
const validBody = require('./middlewares/validBody') // 验证上传参数合法性
const setUser = require('./middlewares/setUser') // 接口设置合法用户
// const cron = require('node-cron');
const { createServer } = require("http");
const { Server } = require("socket.io");
const cors = require('koa2-cors');
const Router = require('koa-router');

const requireDirectory = require('require-directory')
// const tool = require("./tools/tool");
// const {db} = require("./models/db");
const httpServer = createServer(app.callback());
const io = new Server(httpServer, {
    cors: true
})
let rooms = {}
io.on("connection", (socket) => {
    socket.on('setTenantRoom', (data) => {
        if(data && data.roomId && data.tenantId) {
            let roomName = 'tenant' + data.tenantId
            if(!rooms[roomName]) {
                rooms['tenant' + data.tenantId] = data.roomId
            }
            if(rooms[roomName]) socket.join(rooms[roomName])
        }
    })
    socket.on('disconnect', () => {})
})
app.use(catchError); // 统一异常
app.use(
    cors({
        origin: '*',
        maxAge: 5, //指定本次预检请求的有效期，单位为秒。
        credentials: true, //是否允许发送Cookie
        allowMethods: ['POST', 'OPTIONS'], //设置所允许的HTTP请求方法'
        allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'token', 'billid'], //设置服务器支持的所有头信息字段
        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
    })
)
app.use(result);
app.use(koaBody({
    multipart: true, // 处理 multipart/form-data
    formidable: {
        uploadDir: './uploads', // 上传文件保存的目录
        keepExtensions: true,    // 保留文件扩展名
    }
}));
app.use(validBody);
app.use(setUser);
app.use(async (ctx, next) => {
    ctx.io = io;
    let roomId = 0;
    if(ctx.user && ctx.user.tenantId) {
        let roomName = 'tenant' + ctx.user.tenantId;
        roomId = (typeof rooms[roomName] !== 'undefined' && rooms[roomName]) ? rooms[roomName] : '';
    }
    ctx.roomId = roomId;

    await next();
})

requireDirectory(module, './routes', {
    visit: (obj) => {
        if (obj instanceof Router) {
            app.use(obj.routes())
        }
    }}
)
// 定时离店
// try {
//     db.models['contactBfSets'].findAll().then(ret => {
//         if(ret && ret.length > 0) {
//             ret.map(row => {
//                 if(row.autoLeftTime) {
//                     let t = row.autoLeftTime.split(':')
//                     let m = tool.xe.toNumber(t[1])
//                     let h = tool.xe.toNumber(t[0])
//                     let str = `0 ${m} ${h} * * *`
//                     // cron.schedule(str, async () => {
//                     //     await tool.autoLeft()
//                     // })
//                 }
//             })
//         }
//     })
// } catch (e) {
//
// }

// app.listen(996)
//
httpServer.listen(996);
